<template>
  <div>
    <a-form layout="horizontal" :rules="formRules" :model="formData" @finish="handleSubmit">
      <a-form-item>
        <h3><span>找回密码</span></h3>
      </a-form-item>
      <a-form-item required hasFeedback name="mobile">
        <a-input v-model:value="formData.mobile" size="large" placeholder="请输入注册手机号">
          <template #prefix
            ><mobile-outlined type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"
          /></template>
        </a-input>
      </a-form-item>
      <div
        v-if="setting.captcha == 'dragon'"
        id="dragon_captcha"
        class="J__captcha__"
        data-cbfn="callback"
      ></div>
      <TencentCaptcha
        v-if="setting.captcha == 'tencent'"
        ref="Tencent"
        :appId="setting.captcha_app_id"
        @callback="TencSuccess"
      />
      <a-form-item has-feedback name="captcha">
        <a-input v-model:value="formData.captcha" size="large" type="text" placeholder="验证码">
          <template #prefix>
            <mail-outlined type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </template>
          <template #suffix>
            <a-button
              class="getCaptcha"
              tabindex="-1"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              >{{ (!state.smsSendBtn && '获取验证码') || state.time + ' s' }}</a-button
            >
          </template>
        </a-input>
      </a-form-item>
      <a-form-item required hasFeedback name="password">
        <a-input-password
          v-model:value="formData.password"
          size="large"
          type="password"
          placeholder="请输入密码"
        >
          <template #prefix
            ><lock-outlined type="user" :style="{ color: 'rgba(0,0,0,.25)' }"
          /></template>
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          size="large"
          :loading="loading"
          style="width: 60%"
        >
          立即重置
        </a-button>
        <router-link style="float: right" :to="{ name: 'register' }">新用户注册</router-link>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined, MobileOutlined, MailOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { getSmsCaptcha, forgotPassword } from '@/api/system/user'
import { validatePhone, validatePassword, validateCaptcha } from '@/utils/validate'
import { getLoginParam } from '@/api/common'

import { SvgIcon } from '@/components/svg-icon'

export default defineComponent({
  name: 'ForgotPassword',
  components: { UserOutlined, LockOutlined, SvgIcon, MobileOutlined, MailOutlined },
  setup() {
    const state = reactive<any>({
      loading: false,
      setting: {},
      formData: {
        mobile: '',
        authenticate: '',
        token: '',
        password: '',
        captcha: ''
      },
      state: {
        smsSendBtn: false,
        time: 60
      }
    })

    let Tencent = ref<any>(null)

    const router = useRouter()

    onMounted(() => {
      getSetting()
    })

    const getSetting = () => {
      getLoginParam({})
        .then((res) => {
          console.log(res)
          state.setting = res
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const formRules = {
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        },
        {
          validator: validatePassword,
          trigger: ['blur', 'change']
        }
      ],
      mobile: [
        {
          required: true,
          message: '请输入手机号',
          trigger: ['blur', 'change']
        },
        {
          validator: validatePhone,
          trigger: 'change'
        }
      ],
      captcha: [
        {
          required: true,
          message: '请输入验证码',
          trigger: ['blur', 'change']
        },
        {
          validator: validateCaptcha,
          trigger: ['blur', 'change']
        }
      ]
    }

    const initCaptcha = () => {
      new (window as any).Captcha(document.querySelectorAll('.J__captcha__').item(0), {
        // 验证成功时显示
        appId: state.setting.captcha_app_id, //开通后提供
        timerProgressBar: !0, // 是否启用进度条
        timerProgressBarColor: '#07f', // 进度条颜色
        // 验证成回调
        success: function (res) {
          state.formData.token = res.token
          getCaptcha()
        },
        // 验证失败回调
        fail: function () {},
        // 触发验证回调, 不管成功与否
        close: function () {}
      })
    }

    function handleSubmit() {
      if (state.formData.authenticate == '' || state.formData.token == '') {
        requestFailed(null, '请先进行验证')
        return false
      }
      state.loading = true
      forgotPassword(state.formData)
        .then((res) => {
          if (res.code == 200) {
            requestSuccess(null, '重置成功')
            router.push({ name: 'login' })
          } else {
            requestFailed(res)
          }
        })
        .catch((err) => {
          requestFailed(err)
        })
        .finally(() => {
          state.loading = false
          message.destroy()
        })
    }
    const TencSuccess = (info) => {
      state.formData.authenticate = info.randstr
      state.formData.token = info.ticket
      getCaptcha()
    }
    let interval = window.setInterval(() => {})
    function getCaptcha() {
      if (state.state.smsSendBtn == true) {
        return false
      }
      if (!state.formData.mobile) {
        requestFailed(null, '请输入手机号')
        return false
      }
      if (
        state.setting.captcha == 'tencent' &&
        (state.formData.authenticate == '' || state.formData.token == '')
      ) {
        Tencent.value.verifyShow()
        return false
      } else {
        if (state.setting.captcha == 'dragon' && state.formData.token == '') {
          initCaptcha()
          return false
        }
      }
      state.state.smsSendBtn = true
      interval = window.setInterval(() => {
        if (state.state.time-- <= 0) {
          state.state.time = 60
          state.state.smsSendBtn = false
          window.clearInterval(interval)
        }
      }, 1000)
      let hide = message.loading('验证码发送中..', 0)
      getSmsCaptcha({
        phone: state.formData.mobile,
        authenticate: state.formData.authenticate,
        token: state.formData.token,
        type: 'login'
      })
        .then((res) => {
          setTimeout(hide, 1000)
          if (res.code === 200) {
            requestSuccess(null, '验证码获取成功')
          } else {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.state.time = 60
            state.state.smsSendBtn = false
            requestFailed(res)
          }
        })
        .catch((err) => {
          setTimeout(hide, 1)
          clearInterval(interval)
          state.state.time = 60
          state.state.smsSendBtn = false
          requestFailed(err)
        })
    }
    return {
      ...toRefs(state),
      handleSubmit,
      interval,
      formRules,
      getCaptcha,
      Tencent,
      TencSuccess
    }
  }
})
</script>

<style lang="scss" scoped></style>
